/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.bootstrap.client.ui;

import com.cleangwt.bootstrap.client.style.Styles;
import com.cleangwt.uibinder.client.TemplateSupport;
import com.cleangwt.user.client.AnchorActionEvent;
import com.cleangwt.user.client.AnchorActionEvent.AnchorActionHandler;
import com.cleangwt.user.client.AnchorActionEvent.HasAnchorActionHandlers;
import com.cleangwt.user.client.Elements;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.UListElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Widget;

/**
 * A navigator provides hovering and focus style for each item. and this navigator implements
 * {@link HasSelectionHandlers}. each item can contains a anchor element with the 'name' attribute
 * could fire the {@link SelectionEvent} on clicked.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 * @see http://getbootstrap.com/components/#nav
 */
public class Navigator extends Widget implements HasAnchorActionHandlers {

  /**
   * 
   * Creates a Navigator that wraps an existing &lt;ul&gt; element of template.
   * 
   * @param template the template
   * @param element the element to be wrapped
   */
  public static Navigator wrap(TemplateSupport template, Element e) {
    Navigator widget = new Navigator(e);
    template.wrap(widget);
    return widget;
  }

  private boolean selectionHandlerInitialized;

  /**
   * Creates a navigator.
   * 
   */
  public Navigator() {
    this(Document.get().createULElement());
  }

  /**
   * Creates a navigator with the given base style.
   * 
   * @param style the base style
   */
  public Navigator(String style) {
    this();
    this.setStyleBase(style);
  }

  /**
   * This constructor may be used by subclasses to explicitly use an existing element. This element
   * must be a &lt;ul&gt; element.
   * 
   * @param element the element to be used
   */
  protected Navigator(Element element) {
    assert element.getTagName().equalsIgnoreCase(UListElement.TAG);
    setElement(element);
  }

  @Override
  public HandlerRegistration addAnchorActionHandler(AnchorActionHandler handler) {
    if (!this.selectionHandlerInitialized) {
      selectionHandlerInitialized = true;
      this.addDomHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
          AnchorActionEvent.translate(Navigator.this, event);
        }
      }, ClickEvent.getType());
    }
    return addHandler(handler, AnchorActionEvent.getType());
  }

  /**
   * Adds a list item dropdown with the given toggle text and returns the {@link DropdownBuilder} to
   * build it.
   * 
   * @param toggleText the text for toggle element
   * @return the dropdown builder to build a complete list item dropdown
   */
  public DropdownBuilder addDropdown(String toggleText) {
    Element dropdown = DropdownBuilder.createNavDropdown(toggleText);
    this.getElement().appendChild(dropdown);
    return new DropdownBuilder(dropdown);
  }

  /**
   * Adds a element to be wrap in a list item.
   * 
   * @param element the element
   * @return the list item
   */
  protected void addItem(Element element) {
    Element li = Document.get().createLIElement();
    li.appendChild(element);
    getElement().appendChild(li);
  }

  /**
   * Adds a link with the given html.
   * 
   * @param html the html
   * @param href the href
   */
  public void addLink(String html, String href) {
    AnchorElement anchor = Document.get().createAnchorElement();
    anchor.setInnerHTML(html);
    anchor.setHref(href);
    this.addItem(anchor);
  }

  /**
   * Gets index of the active item.
   * 
   * @return the index of active item
   */
  public int getActiveItemIndex() {
    for (int i = 0; i < getElement().getChildCount(); i++) {
      Element li = getElement().getChild(i).cast();
      if (Elements.hasClass(Styles.ACTIVE, li)) {
        return i;
      }
    }
    return -1;
  }

  /**
   * Gets the item count.
   * 
   * @return the item count
   */
  public int getItemCount() {
    return this.getElement().getChildCount();
  }

  /**
   * Gets the index of the given item.
   * 
   * @return the index of item
   */
  public int getItemIndex(Element item) {
    NodeList<Node> childs = this.getElement().getChildNodes();
    for (int i = 0; i < childs.getLength(); i++) {
      if (childs.getItem(i) == item) {
        return i;
      }
    }
    return -1;
  }

  /**
   * Checks whether an active item.
   * 
   * @return whether an active item.
   */
  public boolean isActive() {
    return getActiveItemIndex() >= 0;
  }

  /**
   * Sets an item of index to be active.
   * 
   * @param index the index of item
   */
  public void setActive(int index) {
    for (int i = 0; i < getElement().getChildCount(); i++) {
      Element li = getElement().getChild(i).cast();
      if (i == index) {
        li.addClassName(Styles.ACTIVE);
      } else {
        li.removeClassName(Styles.ACTIVE);
      }
    }
  }

  /**
   * Sets an item of index to be disabled or enabled.
   * 
   * @param index the index of item
   * @param disabled true to disabled false to enabled
   */
  public void setDisabled(int index, boolean disabled) {
    if (index >= 0 && index < getElement().getChildCount()) {
      Element li = getElement().getChild(index).cast();
      if (disabled) {
        li.addClassName(Styles.DISABLED);
      } else {
        li.removeClassName(Styles.DISABLED);
      }
    }
  }

  /**
   * Resets the style name with base nav style and the given type style.
   * 
   * @param style the base style
   */
  public void setStyleBase(String style) {
    assert style != null : "Stye must not be null.";
    setStyleName(Navigators.NAV_STYLE + " " + style);
  }
}
